import { menu } from '@/mock/menuTree.js'

const state = {
  // 必须在store里保存一份菜单，store里的值刷新会重置，在router.beforeEach里作为判断条件。
  menu: [],
  menuUrl: []
}
const whiteList = ['/login', "/404", "/index"]

const mutations = {
  setMenu(state, list) {
    state.menu = list
  },
  setMenuUrl(state, list) {
    state.menuUrl = list
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      // 请求后台路由数据
      setTimeout(() => {
        let res = menu.data
        let urllist = genMenuUrlArr(res)
        // 开启严格模式，不能在actions里直接变更状态。
        // state.menu = res
        // state.menuUrl = urllist.concat(whiteList)
        commit('setMenu', res)
        commit('setMenuUrl', urllist.concat(whiteList))
        resolve(res)
      }, 500)
    })
  },
}

// 生成菜单url数组
const genMenuUrlArr = function (list, arr = []) {
  list.forEach(li => {
    if (li.url) {
      arr.push(li.url)
    }
    if (li.children && li.children.length) {
      genMenuUrlArr(li.children, arr)
    }
  })
  return arr
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}